﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Baddies.Nodes;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate;

namespace Baddies.Utils
{
    /// <summary>
    /// Auxiliary class that takes care of the serialization of a Node tree.
    /// <remarks>
    /// Works by having a reference to the node and serializing itself, so the root
    /// node is also regarded as a reference.
    /// </remarks>
    /// </summary>
    public class NodeSerializer
    {
        /// <summary>
        /// Root node to serialize.
        /// </summary>
        [ContentSerializerAttribute(SharedResource = true)]
        private Node root;

        /// <summary>
        /// Serializes a node to XML.
        /// </summary>
        /// <param name="node">Node to serialize.</param>
        /// <param name="name">Name of the file to serialize to.</param>
        public void Serialize(Node node, string name)
        {
            this.root = node;

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            using (XmlWriter writer = XmlWriter.Create(name, settings))
            {
                IntermediateSerializer.Serialize(writer, this, null);
            }
        }

        /// <summary>
        /// Deserializes the XML file provided and returns the created node.
        /// </summary>
        /// <param name="name">Name of the xml file.</param>
        /// <returns>Node serialized in that file.</returns>
        public Node Deserialize(string name)
        {
            Node node = null;
            XmlReaderSettings settings = new XmlReaderSettings();
            using (XmlReader reader = XmlReader.Create(name, settings))
            {
                NodeSerializer serial = IntermediateSerializer.Deserialize<NodeSerializer>(reader, null);
                node = serial.root;
            }

            return node;
        }
    }
}
